package api

import (
	"context"

	controller "gitee.com/klein-x/biz/controller/utils"
	"gitee.com/klein-x/biz/xutils"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/hlog"
)

type captchaRequest struct {
	Version Version `path:"version" vd:"in($, 1, 2); msg:'未定义的请求'"`
	PhoneID string  `form:"phone" json:"phone" vd:"phone($, 'CN'); msg:'无效的手机号码'"`
}

type captchaResponse struct {
	Message string `json:"message"`
}

func Captcha(ctx context.Context, c *app.RequestContext) {
	var req captchaRequest
	if err := c.BindAndValidate(&req); err != nil {
		ReturnError(c, xutils.Error(API_PARAM_ERROR, err))
		return
	}
	// 生成验证码
	if err := controller.Captcha(ctx, req.PhoneID); err != nil {
		ReturnError(c, err)
		return
	} else {
		var res captchaResponse
		res.Message = "验证码发送成功, 5分钟内有效"
		ReturnSuccess(c, res)
	}
}

type DwloadResRequest struct {
	Version Version `path:"version" vd:"in($, 1, 2); msg:'未定义的请求'"`
	Uuid    string  `form:"uuid" json:"uuid" vd:"len($)==36; msg:'无效的uuid'"`
}

type DwloadResponse struct {
	Type string `json:"type"`
	Data string `json:"data"`
}

func DwloadResource(ctx context.Context, c *app.RequestContext) {
	var req DwloadResRequest
	if err := c.BindAndValidate(&req); err != nil {
		ReturnError(c, xutils.Error(API_PARAM_ERROR, err))
		return
	}
	if res, err := controller.DwloadResource(ctx, req.Uuid); err != nil {
		ReturnError(c, err)
		return
	} else {
		var result DwloadResponse
		result.Type = res.Type
		result.Data = res.Data
		ReturnSuccess(c, result)
	}
}

type UploadResRequest struct {
	Version Version `path:"version" vd:"in($, 1, 2); msg:'未定义的请求'"`
	Type    string  `form:"type" json:"type" vd:"in($,'image'); msg:'无效的type'"`
	Data    string  `form:"data" json:"data" vd:"len($)!=0; msg:'无效的data'"`
}

type UploadResResponse struct {
	UUID string `json:"uuid"`
}

func UploadResource(ctx context.Context, c *app.RequestContext) {
	hlog.Infof("进入api PutImage中")
	var req UploadResRequest
	if err := c.BindAndValidate(&req); err != nil {
		ReturnError(c, xutils.Error(API_PARAM_ERROR, err))
		return
	}
	if uuid, err := controller.UploadResource(ctx, req.Type, req.Data); err != nil {
		ReturnError(c, err)
		return
	} else {
		var result UploadResResponse
		result.UUID = uuid
		ReturnSuccess(c, result)
	}
	hlog.Infof("离开api PutImage中")
}
